class Solution(object):
    def closestToTarget(self, arr, target):
        n = len(arr)
        left = 0
        right = 0
        max_range = 20
        d = {i: set() for i in range(max_range)}
        min_val = float('inf')
        while right < n:
            num = arr[right]
            for i in range(max_range):
                if (num >> i) & 1 == 0:
                    d[i].add(right)
            val = 0
            for i in range(max_range):
                if not d[i]:
                    val |= (1 << i)
            while val <= target and left <= right:
                min_val = min(min_val, target - val)
                for i in range(max_range):
                    if left in d[i]:
                        d[i].remove(left)
                val = 0
                for i in range(max_range):
                    if not d[i]:
                        val |= (1 << i)
                left += 1
            if val > target:
                min_val = min(min_val, val - target)
            right += 1
        return min_val


data = Solution()
arr = [6, 5, 1]
target = 1
print(data.closestToTarget(arr, target))
